package com.jgssp.ad.sdk.topon.adapter;

import android.app.Activity;
import android.content.Context;

import com.anythink.core.api.ATAdConst;
import com.anythink.core.api.ATBiddingListener;
import com.anythink.core.api.ATBiddingResult;
import com.anythink.core.api.MediationInitCallback;
import com.anythink.nativead.unitgroup.api.CustomNativeAdapter;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import cn.jiguang.jgssp.ad.ADJgNativeAd;
import cn.jiguang.jgssp.ad.data.ADJgNativeAdInfo;
import cn.jiguang.jgssp.ad.data.ADJgNativeExpressAdInfo;
import cn.jiguang.jgssp.ad.data.ADJgNativeFeedAdInfo;
import cn.jiguang.jgssp.ad.entity.ADJgAdSize;
import cn.jiguang.jgssp.ad.entity.ADJgExtraParams;
import cn.jiguang.jgssp.ad.error.ADJgError;
import cn.jiguang.jgssp.ad.listener.ADJgNativeAdListener;
import cn.jiguang.jgssp.util.ADJgDisplayUtil;


public class NativeAdapter extends CustomNativeAdapter {
    private String slotId;
    private boolean isAgreePrivacyStrategy;
    private boolean isBidding;
    private ATBiddingListener biddingListener;
    private NativeExpressAd nativeExpressAd;
    private NativeFeedAd nativeFeedAd;
    private ADJgNativeAd nativeAd;

    @Override
    public void loadCustomNetworkAd(final Context context, Map<String, Object> serverExtra, Map<String, Object> localExtra) {

        if (serverExtra.containsKey("slot_id")) {
            slotId = (String) serverExtra.get("slot_id");
        }
        InitManager.getInstance().
                initSDK(context, serverExtra, isAgreePrivacyStrategy, new MediationInitCallback() {
                    @Override
                    public void onSuccess() {
                        startLoad(context);
                    }

                    @Override
                    public void onFail(String errorMsg) {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("-1001", errorMsg);
                        }
                    }
                });

    }

    @Override
    public boolean startBiddingRequest(final Context context, Map<String, Object> serverExtra, Map<String, Object> localExtra, ATBiddingListener biddingListener) {
        this.isBidding = true;
        this.biddingListener = biddingListener;
        if (serverExtra.containsKey("slot_id")) {
            slotId = (String) serverExtra.get("slot_id");
        }
        InitManager.getInstance().
                initSDK(context, serverExtra, isAgreePrivacyStrategy, new MediationInitCallback() {
                    @Override
                    public void onSuccess() {
                        startLoad(context);
                    }

                    @Override
                    public void onFail(String msg) {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("-1001", msg);
                        }
                    }
                });
        return true;
    }


    private void startLoad(final Context context) {
        postOnMainThread(new Runnable() {
            @Override
            public void run() {
                if (!(context instanceof Activity)) {
                    if (isBidding) {
                        if (biddingListener != null) {
                            biddingListener.onC2SBiddingResultWithCache(
                                    ATBiddingResult.fail("context is null or context must be Activity"),
                                    null);
                        }
                    } else {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("-1", "context is null or context must be Activity");
                        }
                    }
                    return;
                }

                int widthPixels = context.getResources().getDisplayMetrics().widthPixels;
                // 创建信息流广告实例
                nativeAd = new ADJgNativeAd((Activity) context);
                // 创建额外参数实例
                ADJgExtraParams extraParams = new ADJgExtraParams.Builder()
                        // 设置整个广告视图预期宽高(目前仅头条平台需要，没有接入头条可不设置)，单位为px，高度如果小于等于0则高度自适应
                        .adSize(new ADJgAdSize(widthPixels, 0))
                        // 设置广告视图中MediaView的预期宽高(目前仅Inmobi平台需要,Inmobi的MediaView高度为自适应，没有接入Inmobi平台可不设置)，单位为px
                        .nativeAdMediaViewSize(new ADJgAdSize((int) (widthPixels - 24 * context.getResources().getDisplayMetrics().density)))
                        .nativeAdPlayWithMute(true)
                        .build();
                // 设置一些额外参数，有些平台的广告可能需要传入一些额外参数，如果有接入头条、Inmobi平台，如果包含这些平台该参数必须设置
                nativeAd.setLocalExtraParams(extraParams);
                nativeAd.setListener(new ADJgNativeAdListener() {
                    @Override
                    public void onAdExpose(ADJgNativeAdInfo adJgNativeAdInfo) {
                        if (adJgNativeAdInfo instanceof ADJgNativeExpressAdInfo) {
                            if (nativeExpressAd != null) {
                                nativeExpressAd.onAdExpose(adJgNativeAdInfo);
                            }
                        } else if (adJgNativeAdInfo instanceof ADJgNativeFeedAdInfo) {
                            if (nativeFeedAd != null) {
                                nativeFeedAd.onAdExpose(adJgNativeAdInfo);
                            }
                        }
                    }

                    @Override
                    public void onAdClick(ADJgNativeAdInfo adJgNativeAdInfo) {
                        if (adJgNativeAdInfo instanceof ADJgNativeExpressAdInfo) {
                            if (nativeExpressAd != null) {
                                nativeExpressAd.onAdClick(adJgNativeAdInfo);
                            }
                        } else if (adJgNativeAdInfo instanceof ADJgNativeFeedAdInfo) {
                            if (nativeFeedAd != null) {
                                nativeFeedAd.onAdClick(adJgNativeAdInfo);
                            }
                        }
                    }

                    @Override
                    public void onAdClose(ADJgNativeAdInfo adJgNativeAdInfo) {
                        if (adJgNativeAdInfo instanceof ADJgNativeExpressAdInfo) {
                            if (nativeExpressAd != null) {
                                nativeExpressAd.onAdClose(adJgNativeAdInfo);
                            }
                        } else if (adJgNativeAdInfo instanceof ADJgNativeFeedAdInfo) {
                            if (nativeFeedAd != null) {
                                nativeFeedAd.onAdClose(adJgNativeAdInfo);
                            }
                        }
                    }

                    @Override
                    public void onAdFailed(ADJgError adJgError) {
                        if (isBidding) {
                            if (biddingListener != null) {
                                biddingListener.onC2SBiddingResultWithCache(
                                        ATBiddingResult.fail(adJgError.getError())
                                        , null
                                );
                            }
                        } else {
                            if (mLoadListener != null) {
                                mLoadListener.onAdLoadError(
                                        "" + adJgError.getCode()
                                        , "" + adJgError.getError()
                                );
                            }
                        }

                    }

                    @Override
                    public void onAdReceive(List<ADJgNativeAdInfo> adInfos) {
                        if (isBidding) {
                            if (biddingListener != null) {
                                if (adInfos == null || adInfos.isEmpty()) {
                                    biddingListener.onC2SBiddingResultWithCache(
                                            ATBiddingResult.fail("adInfo no ad"),
                                            null);
                                } else {
                                    ADJgNativeAdInfo nativeAdInfo = adInfos.get(0);
                                    if (nativeAdInfo instanceof ADJgNativeExpressAdInfo) {
                                        String token = UUID.randomUUID().toString();
                                        nativeExpressAd = new NativeExpressAd(context, (ADJgNativeExpressAdInfo) nativeAdInfo);
                                        biddingListener.onC2SBiddingResultWithCache(
                                                ATBiddingResult.success(100, token, null, ATAdConst.CURRENCY.RMB),
                                                nativeExpressAd);
                                    } else if (nativeAdInfo instanceof ADJgNativeFeedAdInfo) {
                                        String token = UUID.randomUUID().toString();
                                        nativeFeedAd = new NativeFeedAd(context, (ADJgNativeFeedAdInfo) nativeAdInfo);
                                        biddingListener.onC2SBiddingResultWithCache(
                                                ATBiddingResult.success(100, token, null, ATAdConst.CURRENCY.RMB),
                                                nativeFeedAd);
                                    }
                                }
                            }
                        } else {
                            if (mLoadListener != null) {
                                if (adInfos == null || adInfos.isEmpty()) {
                                    mLoadListener.onAdLoadError("-1002", "adInfo no ad");
                                } else {
                                    ADJgNativeAdInfo nativeAdInfo = adInfos.get(0);
                                    if (nativeAdInfo instanceof ADJgNativeExpressAdInfo) {
                                        nativeExpressAd = new NativeExpressAd(context, (ADJgNativeExpressAdInfo) nativeAdInfo);
                                        mLoadListener.onAdCacheLoaded(nativeExpressAd);
                                    } else if (nativeAdInfo instanceof ADJgNativeFeedAdInfo) {
                                        nativeFeedAd = new NativeFeedAd(context, (ADJgNativeFeedAdInfo) nativeAdInfo);
                                        mLoadListener.onAdCacheLoaded(nativeFeedAd);
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onRenderFailed(ADJgNativeAdInfo adJgNativeAdInfo, ADJgError adJgError) {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("" + adJgError.getCode(), "" + adJgError.getError());
                        }
                    }

                    @Override
                    public void onRenderSuccess(ADJgNativeAdInfo adJgNativeAdInfo) {

                    }

                });
                nativeAd.loadAd(getNetworkPlacementId());
            }
        });
    }

    @Override
    public String getNetworkPlacementId() {
        return slotId;
    }

    @Override
    public String getNetworkSDKVersion() {
        return InitManager.getInstance().getNetworkVersion();
    }

    @Override
    public String getNetworkName() {
        return InitManager.getInstance().getNetworkName();
    }

    /**
     * @param context
     * @param isConsent   用户是否授权
     * @param isEUTraffic 是否是欧盟地区
     * @return
     */
    @Override
    public boolean setUserDataConsent(Context context, boolean isConsent, boolean isEUTraffic) {
        isAgreePrivacyStrategy = isConsent;
        return super.setUserDataConsent(context, isConsent, isEUTraffic);
    }

    @Override
    public void destory() {

        if (nativeAd != null) {
            nativeAd.release();
            nativeAd = null;
        }
        if (nativeExpressAd != null) {
            nativeExpressAd.destroy();
            nativeExpressAd = null;
        }
        if (nativeFeedAd != null) {
            nativeFeedAd.destroy();
            nativeFeedAd = null;
        }
        biddingListener = null;
    }
}
